package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";
    // 注意：这里根据实际表名调整，你提供的表名是 shixun
    private static final String TABLE_NAME = "shixun";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        if ("changePassword".equals(action)) {
            handleChangePassword(request, response, out);
        }
    }

    // 处理密码修改逻辑
    private void handleChangePassword(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        String username = request.getParameter("username");
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        // 校验参数
        if (username == null || oldPassword == null || newPassword == null
                || username.trim().isEmpty() || oldPassword.trim().isEmpty() || newPassword.trim().isEmpty()) {
            out.println("{\"success\": false, \"error\": \"参数不完整，请检查输入\"}");
            return;
        }

        // 【关键修改】移除MD5加密，直接用明文
        String oldPwdEncrypted = oldPassword;
        String newPwdEncrypted = newPassword;

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

            // 1. 验证旧密码
            String checkSql = "SELECT id FROM " + TABLE_NAME + " WHERE username = ? AND mpwd = ?";
            stmt = conn.prepareStatement(checkSql);
            stmt.setString(1, username);
            stmt.setString(2, oldPwdEncrypted);
            rs = stmt.executeQuery();

            if (!rs.next()) {
                out.println("{\"success\": false, \"error\": \"旧密码错误，请重新输入\"}");
                return;
            }

            // 2. 更新新密码
            String updateSql = "UPDATE " + TABLE_NAME + " SET mpwd = ? WHERE username = ?";
            stmt = conn.prepareStatement(updateSql);
            stmt.setString(1, newPwdEncrypted);
            stmt.setString(2, username);
            int affectedRows = stmt.executeUpdate();

            if (affectedRows > 0) {
                request.getSession().invalidate(); // 销毁Session
                out.println("{\"success\": true, \"message\": \"密码修改成功，请重新登录\"}");
            } else {
                out.println("{\"success\": false, \"error\": \"密码修改失败，请稍后重试\"}");
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            out.println("{\"success\": false, \"error\": \"系统错误：" + e.getMessage() + "\"}");
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 密码加密方法，使用 MD5 加密示例
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            // 加密失败时，返回原始密码（仅用于极端情况，实际应处理异常）
            return password;
        }
    }
}